package com.qire.manhua.model.viewModel.impl;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.view.View;

import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.qire.common.GlideApp;
import com.qire.common.SummerApp;
import com.qire.common.basic.ColorUtil;
import com.qire.common.basic.ObjectUtil;
import com.qire.common.collect.ListUtil;
import com.qire.common.model.entity.UserEntity;
import com.qire.common.support.base.BaseViewModel;
import com.qire.common.support.base.IViewModel;
import com.qire.common.widget.adapter.auto.AutoVariable;
import com.qire.common.widget.adapter.auto.SummerBannerAdapter;
import com.qire.common.widget.adapter.auto.SummerComplexBindAdapter;
import com.qire.common.widget.adapter.auto.annotation.AdapterEntityBind;
import com.qire.manhua.R;
import com.qire.manhua.controller.RecommendVipZoneController;
import com.qire.manhua.dal.service.RecommendVipZoneService;
import com.qire.manhua.databinding.LayoutHomeRecommendVipBannerItemBinding;
import com.qire.manhua.databinding.LayoutHomeRecommendVipSlideZoneBinding;
import com.qire.manhua.model.entity.AppAdvert;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;
import androidx.databinding.library.baseAdapters.BR;
import androidx.lifecycle.MutableLiveData;
import androidx.palette.graphics.Palette;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView.Adapter;
import androidx.recyclerview.widget.RecyclerView.LayoutManager;

/**
 * 首页-推荐页-VIP专区
 */
public class RecommendVipZoneViewModel extends BaseViewModel<IViewModel> {

    private RecommendVipZoneService vipZoneService = new RecommendVipZoneService(this);

    private final VipSlideZoneViewModel slideZoneViewModel = new VipSlideZoneViewModel();

    private final ArrayList<AutoVariable> moduleList = new ArrayList();
    private final SummerComplexBindAdapter moduleAdapter = new SummerComplexBindAdapter(moduleList);


    //region    #附加管理 begin
    /**
     * 附加属性绑定
     */
    public void onAddition(RecommendVipZoneController controller) {
        refreshUI();
        slideZoneViewModel.setEventProcess(controller);
        moduleAdapter.setEventProcess(controller);
    }

    /**
     * 清理函数，在Activity退出时，ViewModel生命周期到期会被回收，调用该事件，
     * 页面由于切换、横竖屏转换、内存回收等情况并不会影响到ViewModel的生命周期。
     */
    @Override
    protected void onCleared() {
        super.onCleared();
        slideZoneViewModel.setEventProcess(null);
        moduleAdapter.setEventProcess(null);
    }
    //endregion #附加管理 end

    // region    #业务
    public void loadVipZoneData() {
        vipZoneService.loadPageData();
    }

    public void clearBannerList() {
        slideZoneViewModel.clearBannerList();
    }
    public void addVipBannerItemViewModel(AppAdvert appAdvert) {
        slideZoneViewModel.addBannerItemViewModel(appAdvert);
    }
    public void refreshBannerAdapter() {
        slideZoneViewModel.refreshBannerAdapter();
    }

    public void clearModuleList() {
        moduleAdapter.notifyItemRangeRemoved(1, moduleList.size() -1);
        moduleList.clear();
        moduleList.add(slideZoneViewModel);
    }
    public void addModule(AutoVariable[] modules) {
        if(ObjectUtil.nonNull(modules)) {
            for(AutoVariable module : modules) {
                if(ObjectUtil.nonNull(module)) {
                    moduleList.add(module);
                }
            }
        }
    }
    public void refreshModuleAdapter() {
        moduleAdapter.notifyItemChanged(0, "full");
    }

    // endregion #业务

    // region #UI操作

    public void refreshUI() {
        refreshEmptyDataUI();
        refreshVipPanelUI();
    }

    public void refreshVipPanelUI() {
        slideZoneViewModel.notifyChange();
    }

    public void refreshEmptyDataUI() {
        boolean isEmpty = false;
        set("errorLayoutPanelVisible", isEmpty ? View.VISIBLE : View.GONE);
    }

    public void changeBannerBackground(int index) {
        slideZoneViewModel.changeBannerBackground(index - 1);
    }

    // endregion

    // region #UI属性绑定

    public MutableLiveData<Integer> getErrorLayoutPanelVisible() {
        return get("errorLayoutPanelVisible");
    }

    public Adapter getModuleAdapter() {
        return moduleAdapter;
    }

    public LayoutManager getModuleLayoutManager() {
        return  new LinearLayoutManager(null, LinearLayoutManager.VERTICAL, false);
    }

    // endregion

    public class VipBannerItemViewModel extends BaseObservable implements AutoVariable<LayoutHomeRecommendVipBannerItemBinding> {

        private final AppAdvert appAdvert;

        private int themeColor = Color.TRANSPARENT;

        public VipBannerItemViewModel(AppAdvert appAdvert) {
            this.appAdvert = appAdvert;

            // 提取 Banner 主题颜色，作为显示背景
            GlideApp.with(SummerApp.summerApp())
                    .asBitmap()
                    .load(appAdvert.advertImage)
                    .into(new CustomTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                            if(ObjectUtil.nonNull(resource)) {
                                Palette palette = Palette.from(resource).generate();
                                Palette.Swatch vibrant = palette.getMutedSwatch();     //获取柔和的色调
                                themeColor = vibrant.getRgb();
                            }
                        }
                        @Override
                        public void onLoadCleared(@Nullable Drawable placeholder) {}
                    });
        }

        @Override
        public void bindVariable(LayoutHomeRecommendVipBannerItemBinding viewBind) {
            viewBind.setVipBannerItemViewModel(this);
        }

        public void doAction() {
            appAdvert.doAction();
        }

        public int themeColor() {
            return themeColor;
        }

        @Bindable
        public String getAdvertImage() {
            return appAdvert.advertImage;
        }
    }

    @AdapterEntityBind(viewRid = R.layout.layout_home_recommend_vip_slide_zone)
    public class VipSlideZoneViewModel extends BaseObservable implements AutoVariable<LayoutHomeRecommendVipSlideZoneBinding> {

        private final ArrayList<VipBannerItemViewModel> bannerList = new ArrayList<>();
        private final SummerBannerAdapter bannerAdapter = new SummerBannerAdapter(bannerList, R.layout.layout_home_recommend_vip_banner_item);

        private String bannerBackground = "#18241b";

        public void setEventProcess(AutoVariable autoVariable) {
            bannerAdapter.setEventProcess(autoVariable);
        }

        public void clearBannerList() {
            bannerAdapter.notifyItemRangeRemoved(0, bannerList.size());
            bannerList.clear();
        }

        public void addBannerItemViewModel(AppAdvert appAdvert) {
            bannerList.add(new VipBannerItemViewModel(appAdvert));
        }

        public void refreshBannerAdapter() {
            bannerAdapter.notifyItemChanged(0, "full");
        }

        public void changeBannerBackground(int index) {
            // todo：临时修复banner无限循环时出现的溢出问题，零时调整，在banner无限循环修复后，应该删除下面这句话。
            index = ListUtil.isEmpty(bannerList) ? 0 : index % bannerList.size();

            if(ListUtil.range(bannerList, index)) {
                VipBannerItemViewModel itemViewModel = bannerList.get(index);
                if(ObjectUtil.nonNull(itemViewModel)) {
                    int color = ColorUtil.RGB.colorBurn(itemViewModel.themeColor(), 0.3f);
                    bannerBackground = ColorUtil.RGB.from(color);
                    notifyPropertyChanged(BR.bannerBackground);
                }
            }
        }


        @Override
        public void bindVariable(LayoutHomeRecommendVipSlideZoneBinding viewBind) {
            viewBind.setVipSlideZoneViewModel(this);
        }

        @Bindable
        public String getBannerBackground() {
            return bannerBackground;
        }

        @Bindable
        public int getVipHeadWearVisible(){
            return UserEntity.self.isVip() ? View.VISIBLE : View.GONE;
        }

        @Bindable
        public String getUserHeadImage() {
            if (UserEntity.self.isLogin())
                return UserEntity.self.getPortrait();
            return "";
        }

        @Bindable
        public CharSequence getUserNickname() {
            if (UserEntity.self.isLogin())
                return UserEntity.self.getName();
            return "大人！点这里登录";
        }

        @Bindable
        public int getVipTipsVisible(){
            return UserEntity.self.isLogin() ? View.VISIBLE : View.GONE;
        }

        @Bindable
        public CharSequence getVipTips() {
            return UserEntity.self.isVip() ? String.format("将于 %s 过期", UserEntity.self.getShortVipExpirationTime())
                    : "开通会员,享受多重特权!!";
        }

        @Bindable
        public int getBuyMembershipBtnVisible(){
            return UserEntity.self.isLogin() ? View.VISIBLE : View.GONE;
        }

        @Bindable
        public String getBuyMembershipBtnText(){
            return UserEntity.self.isVip() ? "立即续费" : "立即开通";
        }

        public SummerBannerAdapter getBannerAdapter() {
            return bannerAdapter;
        }

    }

}
